package com.corpdata.common.upload.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.corpdata.common.upload.dao.SysAttachmentMapper;
import com.corpdata.common.upload.entity.SysAttachment;
import com.corpdata.common.upload.service.SysAttachmentService;
import com.corpdata.common.utils.CorpdataUtil;
import com.corpdata.core.base.AbstractBaseService;
import com.corpdata.system.security.shiro.util.UserUtil;

/**
 * 
 * 
 * @author wu
 * @email 64088839@qq.com
 * @date 2018-07-26 10:32:32
 */
@Service
@Transactional
public class SysAttachmentServiceImpl extends AbstractBaseService<SysAttachment> implements SysAttachmentService {
	@Value("${web.upload.file_path}")
    private String filePath;
	@Autowired
	private SysAttachmentMapper mapper;

	public Map<String, Object> insert(String docunid,HttpServletRequest request) throws IOException {
		String pat=filePath;//获取文件保存路径
        String sqlPath="/"+CorpdataUtil.getNowTime("yyyyMM")+"/";
        String fileName="";
        String myFileName="";
        String extName="";
        long size = 0;
        String sizeUnit = "KB";
		Date date = new Date();
		String id=CorpdataUtil.getUUID();
		SysAttachment record=new SysAttachment();
		record.setId(id);
		record.setDocunid(docunid);
		record.setCreater(UserUtil.getCurrentUserid());
		record.setCreated(date);
		record.setModified(date);
		record.setDel(0);
		
		
		// TODO Auto-generated method stub
        //创建一个通用的多部分解析器  
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
        //判断 request 是否有文件上传,即多部分请求  
        if(multipartResolver.isMultipart(request)){  
            //转换成多部分request    
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
            //取得request中的所有文件名  
            Iterator<String> iter = multiRequest.getFileNames();  
            while(iter.hasNext()){  
                //取得上传文件  
                MultipartFile file = multiRequest.getFile(iter.next());  
                if(file != null){  
                    //取得当前上传文件的文件名称  
                    myFileName = file.getOriginalFilename();
                    if(file.getSize()>1024*1024*1024){
						size = file.getSize()/1024/1024/1024;
						sizeUnit = "GB";
					}else if(file.getSize()>1024*1024){
						size = file.getSize()/1024/1024;
						sizeUnit = "MB";
					}else{
						size = file.getSize()/1024;
					}
                    fileName=myFileName;
                    if (myFileName.lastIndexOf(".") >= 0) {
						//当前文件拓展名
                    	extName = myFileName.substring(myFileName.lastIndexOf("."));
					}
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在  
                    if(myFileName.trim() !=""){  
                        //System.out.println(myFileName);  
                        //重命名上传后的文件名  按照id进行命名
                        if(extName!=""){
                        	fileName = id+extName;  
                        }
                        //定义上传路径  
                        try {
                            
                            //E:\工作目录\代码\maven.1517987783712\biz\src\main\resources\static\image
                            File fileDir=new File(pat+sqlPath);
                            
                            if (!fileDir.exists()) { //如果不存在 则创建     
                                 fileDir.mkdirs();    
                            } 
                            String path=pat+sqlPath+fileName;
                            //System.out.println("path:"+path);
                            //存文件
                            File localFile = new File(path);  
                            file.transferTo(localFile);
                            
                            record.setFileSize(size+sizeUnit);
                            record.setFileName(myFileName);
                            record.setFilePath(sqlPath);
                            record.setFileType(extName);
                        } catch (IllegalStateException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }  
                }  
            }  
        }
       // Map<String, Object> rs = CorpdataUtil.getDefaultInsertMsgMap();
        Map<String,Object> rs = new HashMap<String,Object>();
		rs.put("msg", "保存失败!");
		rs.put("success", false);
		if (mapper.insert(record)>0) {
			rs.put("msg", "保存成功!");
			rs.put("success", true);
			rs.put("id", id);
			rs.put("sqlPath", sqlPath);
			rs.put("fileName", fileName);
			rs.put("name", myFileName);
			rs.put("extName", extName);
		} 
		return rs;
	}
	
	public SysAttachment selectId(String id){
		return mapper.selectId(id);
	}
	
	public void updateDel(String imageId,String docunid){
		if(mapper.updateDel(docunid)>0){
			String[] image=imageId.split(",");
			for(String ima:image){
				SysAttachment sysAttachment=new SysAttachment();
				sysAttachment.setModified(new Date());
				sysAttachment.setDel(1);
				sysAttachment.setId(ima);
				super.update(sysAttachment);
			}
		}
	}
	
	public List<SysAttachment> findByDocUnid(String docUnid){
		return mapper.findByDocUnid(docUnid);
	}
}
